package qinggui.mlz.smsservice.crond;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import qinggui.mlz.smsservice.entity.SmsCrond;
import qinggui.mlz.smsservice.infrastructure.SmsTemplate;
import qinggui.mlz.smsservice.mapper.SmsCrondMapper;


import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/* ------------- 定时任务扫描 ------------- */
@Slf4j
@Component
public class SmsSendCrond {

    @Autowired
    private SmsCrondMapper smsCrondMapper;
    @Autowired
    private SmsTemplate smsTemplate;

    // 5秒执行一次
    @Scheduled(fixedRate = 5000)
    public void cronSend() {
        // 扫描定时任务表中的未发送的手机号，有且没有发送过的才发送
        List<SmsCrond> smsCronds = smsCrondMapper.listUnSendCronSend();
        List<SmsCrond> updateList = new ArrayList<>();

        for (SmsCrond smsCrond : smsCronds) {
            String phone = smsCrond.getPhone();
            String result;
            try {
                result = smsTemplate.send(phone, smsCrond.getContent());
            } catch (Exception e) {
                result = "Exception: " + e.getMessage();
            }

            // 更新状态
            smsCrond.setStatus((byte) 1); // 1表示已处理
            smsCrond.setUpdateTime(LocalDateTime.now());

            if (!"OK".equals(result)) {
                smsCrond.setFailMsg(result);
            }

            updateList.add(smsCrond);
        }

        // 批量更新
        if (!updateList.isEmpty()) {
            try {
                Integer updateTotal =smsCrondMapper.batchUpdate(updateList);
                for (SmsCrond smsCrond : updateList) {
                    if (smsCrond.getFailMsg() == null) {
                        log.info("该手机号发送成功：{}", smsCrond.getPhone());
                    } else {
                        log.error("该手机号发送失败：{}", smsCrond.getPhone());
                    }
                }
            } catch (Exception e) {
                log.error("批量更新短信发送状态失败", e);
            }
        }
    }

}
